package com.panlm.kafka.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class InterceptorProducer {

    public static String KAFKA_CLUSTER = "hadoop102:9092,hadoop103:9092,hadoop104:9092";
    private KafkaProducer<String, String> producer;
    private String topic = "bigdata";

    @Before
    public void before() {
        Properties properties = new Properties();
        //kafka 集群，broker-list
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA_CLUSTER);
        //ack 应答机制
        properties.put(ProducerConfig.ACKS_CONFIG, "all");
        //重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG, 1);
        //批次大小
        properties.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384);
        //等待时间
        properties.put(ProducerConfig.LINGER_MS_CONFIG, 1);
        //RecordAccumulator缓冲区大小
        properties.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432);

        //设置key和vulue序列化
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        //构建拦截链
        List<String> interceptors = new ArrayList<>();
        interceptors.add("com.panlm.kafka.interceptor.TimeInterceptor");
        interceptors.add("com.panlm.kafka.interceptor.CounterInterceptor");
        properties.put(ProducerConfig.INTERCEPTOR_CLASSES_CONFIG, interceptors);


        producer = new KafkaProducer<>(properties);

    }

    //必须要关闭producer，这样才会调用interceptor的close方法
    @After
    public void after() {
        producer.close();
    }

    @Test
    public void testSendWithInterceptor() {
        for (int i = 0; i < 10; i++) {
            ProducerRecord<String, String> record = new ProducerRecord<>(topic, Integer.toString(i),"message" + i);
            producer.send(record);
        }
    }
}
